package com.supeng.PMdepot.base;

import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.supeng.PMdepot.R;
import com.supeng.PMdepot.event.NetworkChangeEvent;
import com.supeng.PMdepot.receiver.NetworkConnectChangedReceiver;
import com.supeng.PMdepot.util.KeyboardUtils;
import com.supeng.PMdepot.util.Utils;
import com.supeng.PMdepot.util.actionbar.LightStatusBarUtils;
import com.supeng.PMdepot.util.actionbar.ToolbarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Unbinder;

/**
 * Created by Supeng on 2018/8/15.
 */

public class BaseActivity extends AppCompatActivity {
    protected Context mContext;
    protected boolean mCheckNetWork = true; //默认检查网络状态
    View mTipView;
    WindowManager mWindowManager;
    WindowManager.LayoutParams mLayoutParams;
    private NetworkConnectChangedReceiver networkConnectChangedReceiver;
    private boolean mReceiverTag = false;   //广播接受者标识
    public Unbinder unbinder;
    protected ImageView iv_back;
    private PowerManager powerManager = null;
    private PowerManager.WakeLock wakeLock = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            //标题栏颜色
            ToolbarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.blueColorAppKey));
            //深色主题 true字颜色为深色 false 为白色标题字
            LightStatusBarUtils.setLightStatusBar(this, false);
        mContext = this;
        //7.0及以上必须使用动态注册广播
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (!mReceiverTag) {     //在注册广播接受者的时候 判断是否已被注册,避免重复多次注册广播
                IntentFilter filter = new IntentFilter();
                mReceiverTag = true;    //标识值 赋值为 true 表示广播已被注册
                filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
                filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
                networkConnectChangedReceiver = new NetworkConnectChangedReceiver();
                this.registerReceiver(networkConnectChangedReceiver, filter);
            }
        }
        initTipView();//初始化提示View
        EventBus.getDefault().register(this);
        //屏幕适配 https://mp.weixin.qq.com/s/d9QCoBP6kV9VSWvVldVVwA 今日头条方法 改变了ppi
        //默认以360dp适配
        //density px/dp 的值
        //改变了ppi
        setCustomDensity(getApplication());
        // 获取设备电源锁屏
        powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK , getActivity().getClass().getSimpleName());
        if (wakeLock != null) {
            wakeLock.setReferenceCounted(false);
            //请求电源锁
            wakeLock.acquire();
        }
    }
    private static float mDensity;
    private static float mScaledDensity;
    private static float mDp=360;
    private void setCustomDensity(final Application application) {
        final DisplayMetrics appDisPalyMetrics=application.getResources().getDisplayMetrics();
        if(mDensity==0){
            mDensity=appDisPalyMetrics.density;
            mScaledDensity=appDisPalyMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                        if(newConfig!=null&&newConfig.fontScale>0){
                            final DisplayMetrics appDisPalyMetricsNew=application.getResources().getDisplayMetrics();
                            mScaledDensity=appDisPalyMetricsNew.scaledDensity;
                        }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }
        //        android中的dp在渲染前会将dp转为px，计算公式：
        //        px = density * dp;
        //        density = dpi / 160;
        //        px = dp * (dpi / 160);
        //        dpi＝（√（横向分辨率^2+纵向分辨率^2））/屏幕尺寸
        //以屏幕宽度调整密度 也可以用屏幕高度调整密度
        final float targetDensity=appDisPalyMetrics.widthPixels/mDp;
        //字体密度
        final float targetScaledDensity=targetDensity*(mScaledDensity/mDensity);
        //屏幕dpi ppi
        final int targetDensityDpi=(int)(targetDensity*160);
        appDisPalyMetrics.density=targetDensity;
        appDisPalyMetrics.scaledDensity=targetScaledDensity;
        appDisPalyMetrics.densityDpi=targetDensityDpi;
    }
    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        if (iv_back != null) {
            iv_back.setOnClickListener(new View.OnClickListener() {
                public final void onClick(View v) {
                    KeyboardUtils.hideSoftInput(iv_back,getActivity());
                    finish();
                }
            });
        }

    }
    @Override
    protected void onResume() {
        super.onResume();
        //MobclickAgent.onResume(this);
        //在无网络情况下打开APP时，系统不会发送网络状况变更的Intent，需要自己手动检查
        hasNetWork(Utils.isConnected(mContext));
    }

    @Override
    protected void onPause() {
        super.onPause();
      //  MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (mReceiverTag) {   //判断广播是否注册
                mReceiverTag = false;   //Tag值 赋值为false 表示该广播已被注销
                if (networkConnectChangedReceiver != null) {
                    this.unregisterReceiver(networkConnectChangedReceiver);
                }
            }
        }
        //手动释放
        if(unbinder!=null) {
            unbinder.unbind();
        }
        if ( wakeLock != null ) {
            //取消电源锁
            wakeLock.release();
        }
    }

    @Override
    public void finish() {
        super.finish();
        //当提示View被动态添加后直接关闭页面会导致该View内存溢出，所以需要在finish时移除
        if (mTipView != null && mTipView.getParent() != null) {
            mWindowManager.removeView(mTipView);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetworkChangeEvent(NetworkChangeEvent event) {
        hasNetWork(event.isConnected);
    }

    private void hasNetWork(boolean has) {
        if (isCheckNetWork()) {
            if (has) {
                if (mTipView != null && mTipView.getParent() != null) {
                    mWindowManager.removeView(mTipView);
                }
            } else {
                if (mTipView.getParent() == null) {
                    mWindowManager.addView(mTipView, mLayoutParams);
                }
            }
        }
    }

    public void setCheckNetWork(boolean checkNetWork) {
        mCheckNetWork = checkNetWork;
    }

    public boolean isCheckNetWork() {
        return mCheckNetWork;
    }

    private void initTipView() {
        LayoutInflater inflater = getLayoutInflater();
        mTipView = inflater.inflate(R.layout.layout_network_tip, null); //提示View布局
        //悬浮框  PixelFormat.TRANSLUCENT 半透明
        mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        mLayoutParams = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT);
        //使用非CENTER时，可以通过设置XY的值来改变View的位置
        mLayoutParams.gravity = Gravity.TOP;
        mLayoutParams.x = 0;
        mLayoutParams.y = 0;
    }
    public Activity getActivity(){
        return  this;
    }
}

